<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User  extends Base_Controller
{
    private $user_id;

    private  $page_limit = 10;

    private $url='http://www.wayatrip.com';
    //评论图片目录
    Const COMMENTS_PIC = "/home/ali0t4/source/waya/webroot/web/upload/tourist_pic/";
    //评论图片在数据库中的目录
    Const COMMENTS_PIC_INDB = "/upload/tourist_pic/";
    //景点评论图片目录
    Const SCENIC_COMMENTS_PIC = "/home/ali0t4/source/waya/webroot/web/upload/scenic_comments_pic/";    
    Const SCENIC_COMMENTS_PIC_INDB = "/upload/scenic_comments_pic/";
    //身份认证图片目录
    Const IDENTITY_PIC = "/home/ali0t4/source/waya/webroot/web/upload/icon/guider/identity_pic/";    
    Const IDENTITY_PIC_INDB = "/upload/icon/guider/identity_pic/";
    //头像目录
    Const USERICON_PIC = "/home/ali0t4/source/waya/webroot/web/upload/icon/";       
    Const USERICON_PIC_INDB = "/upload/icon/";

    public function __construct()
    {
        parent::__construct();
        $this->load->model('userv2info_model');
        $this->load->model('userchat_model');
        $this->load->model('userv2_model');
        $this->load->model('apporder_model');
        $this->load->model('notice_model');
        $this->load->model('apporderlog_model');
        $this->load->model('appordershensu_model');
        $this->load->model('trackcomments_model');
        $this->load->model('userv2mobile_model');
        $this->load->model('jingdian_model');
        $this->load->library('Myusersubscribe');
       // $this->load->library('MyEmail');
        $this->load->library('PHPEmail');
        $this->load->library('MySms');
        $this->load->helper('captcha');
        if(!isset($_SESSION)){
            session_start();
        }
        if(!isset($_SESSION['is_login'])||$_SESSION['is_login'] != 1) $this->error('未登录');

        $this->user_id = $_SESSION['uid'];
        $this->usertype = strtoupper($_SESSION['user_type']);

    }

    /**
     * 基本信息
     */
    public function index()
    {
        $userv2info = $this->userv2info_model->getUserV2Info(array('uvu.uid' => $this->user_id));
        if(!empty($userv2info)){
        	unset($userv2info['telCode']);
        	unset($userv2info['telNum']);
        	unset($userv2info['userPhone']);
        	unset($userv2info['userId']);
        }
        $this->success($userv2info);
    }
    /**
     * 微信活动用户登记
     */
    public function addwxactuser()
    {
    	if(isset($_POST) && !empty($_POST)){
    		$this->load->model('wx_act');
    		//检查用户是否已经报名
    		$isnull=$this->wx_act->getactuser(array("uid" => $this->user_id));
    		if(!empty($isnull)){
    			$this->success("您已经报名");
    		}
    		
    		$data=array(
    			"actName"=>$_POST['act'],
    			"uid"    =>$this->user_id,
    			"wxnum"  =>$_POST['wxnum'],
    			"name"   =>$_POST['name'],
    		    "created"=>time(),
    		);
    		    		
    		$res=$this->wx_act->addactuser($data);
    		
    		if($res){
    			$this->success("报名成功");
    		}else{
    			$this->error("系统错误，请重试");
    		}
    		
    	} else {
    		$this->error("系统错误，请重试");
    	}
    	
    }

    /**
     * 我的订单
     */
    public function myorderlist()
    {
        //页码
        $page = 1;
        if(isset($_GET['page']) && is_numeric($_GET['page'])){
            $page = $_GET['page'];
        }
        $offset = ($page - 1) * $this->page_limit;

        //每页数量
        if(!isset($_GET['size']) || !is_numeric($_GET['size'])){
            $limit = $this->page_limit;
        }else{
            $limit = $_GET['size'];
        }

        if(isset($_GET['status']) && is_numeric($_GET['status']) && $_GET['status'] == 1){
            $orderlist = $this->apporder_model->orderlist('uid = '.$this->user_id.' and status in (0,1,2,3,4,5,7,31,99)', $offset, $limit);
        }else{
            $orderlist = $this->apporder_model->orderlist('uid = '.$this->user_id.' and status in (6,32)', $offset, $limit);
        }

        $this->success(array('data' => $orderlist, 'page' => $page));
    }

    /**
     * 订单详情
     */
    public function myorderdetail()
    {
        if(!isset($_GET['id']) || !is_numeric($_GET['id'])) $this->error('order id not be null');
        $orderDetail = $this->apporder_model->orderDetail(array('ao.uid' => $this->user_id, 'ao.id' => $_GET['id']));

        $this->success($orderDetail);
    }

    /**
     * 申请退款
     */
    public function shensu()
    {
        $orderId = isset($_POST['order_id']) && is_numeric($_POST['order_id']) ? $_POST['order_id'] : null;
        $orderInfo = $this->apporder_model->orderDetail(array('ao.uid' => $this->user_id, 'ao.id' => $orderId));
        
        if(empty($orderInfo)) $this->error('订单不存在');
        //不是行程中的订单
		if($orderInfo['status_id'] != 3) {
			$err=$this->apporder_model->ordererror('SHENSU',$orderInfo['status_id']);
			$this->error($err);
		}
        //更改订单状态
        $res = $this->apporder_model->updateOrder(array('status' => 31), array('id' => $orderId, 'uid' => $this->user_id));
        if($res){
        	$shensu = $this->appordershensu_model->getShensu(array('orderId' => $orderId));
        	//判定退款申请是否已经存在
            if(!empty($shensu)){
                $this->appordershensu_model->editShensu(array('shensuStatus' => '未处理'), array('id' => $shensu['id']));
            }else{
                $this->appordershensu_model->addShensu(array('orderId' => $orderId,
                                                            'shensuStatus' => '未处理',
                                                            'handleTime' => NULL,
                                                            'shensuCreated' => time()
                                                            ));
            }
            $this->apporderlog_model->addOrderLog(array('orderId' => $orderId,'log' =>"游客向哇吖发出退款申请",'created' => time()));
            $this->apporderlog_model->addOrderLog(array('orderId' => $orderId,'log' =>"哇吖开始受理游客的申诉申请，并会于1个工作日内与游客取得联系",'created' => time()));
            //提醒
            $guider = $this->userv2_model->getUser(array('uid' => $orderInfo['shopId']));
            $tourist = $this->userv2_model->getUser(array('uid' => $this->user_id));
            $startDay = $orderInfo['startDay'];
            $endDay = $orderInfo['stopDay'];
            $title = $orderInfo['orderName'];
            $touristName = $tourist['userName'];
            $guiderName = $guider['userName'];
            $tourist_id = $this->user_id;
            $guider_id = $guider['uid'];
            //网页提醒
            $guider_msg = "游客{$touristName}针对{$startDay}至{$endDay}的行程《{$title}》向您发出了退款申请，哇吖将在近期协调处理";
            $tourist_msg = "哇吖已收到您关于{$guiderName}提供的{$startDay}至{$endDay}的行程《{$title}》的退款申请，哇吖将在近期协调处理";
            $this->notice_model->addNotice(array('sendUser' => -10, 'receiveUser' => $guider_id, 'type' => 0,
                                                 'message' =>$guider_msg , 'created' => time()));
            $this->notice_model->addNotice(array('sendUser' => -10, 'receiveUser' => $tourist_id, 'type' => 0,
                                                 'message' =>$tourist_msg , 'created' => time()));
            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 完成行程
     */
    public function finish()
    {
        $orderId = isset($_POST['order_id']) && is_numeric($_POST['order_id']) ? $_POST['order_id'] : null;
		$orderInfo = $this->apporder_model->orderDetail(array('ao.uid' => $this->user_id, 'ao.id' => $orderId));

		if(empty($orderInfo)) $this->error('订单不存在');
		//不是行程中的订单
		if($orderInfo['status_id'] != 3 && $orderInfo['status_id'] != 32) {
			$err=$this->apporder_model->ordererror('FINISH',$orderInfo['status_id']);
			$this->error($err);
		}
		//更改订单状态
        $res = $this->apporder_model->updateOrder(array('status' => 99), array('id' => $orderId, 'uid' => $this->user_id));
        if($res){
            //订单日志
			$this->apporderlog_model->addOrderLog(array('orderId' => $orderId,'log' =>"行程已经完成，哇吖将在1-2工作日内向行程提供者执行打款操作",'created' => time()));
            $startDay = $orderInfo['startDay'];
            $endDay = $orderInfo['stopDay'];
            $title = $orderInfo['orderName'];
			$tourist_id = $this->user_id;
			//网页提醒
            $tourist_msg = "您已顺利完成{$startDay}至{$endDay}《{$title}》，别忘了到个人中心我的点评中留下您的点评哦！";
            $this->notice_model->addNotice(array('sendUser' => -10, 'receiveUser' => $tourist_id, 'type'=>0,
				'message' =>$tourist_msg , 'created' => time()));
			//短信提醒
			$tourist = $this->userv2_model->getUser(array('uid' => $tourist_id));
            $mobile = '+'.$tourist['telCode'].$tourist['telNum'];
			if($orderInfo['telNum']){
                $tpl_id = 1196621;
                $tpl_value = "#start_date#={$startDay}&#end_date#={$endDay}&#service#={$title}";
                $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $mobile);
            }

            $this->success();
        }else{
            $this->error();
        }
    }

    /**
     * 预定记录
     */
    public function orderlist()
    {
        //页码
        $page = 1;
        if(isset($_GET['page']) && is_numeric($_GET['page'])){
            $page = $_GET['page'];
        }
        $offset = ($page - 1) * $this->page_limit;

        //每页数量
        if(!isset($_GET['size']) || !is_numeric($_GET['size'])){
            $limit = $this->page_limit;
        }else{
            $limit = $_GET['size'];
        }

        if(isset($_GET['status']) && is_numeric($_GET['status']) && $_GET['status'] == 1){
            $orderlist = $this->apporder_model->getDealOrder(' a.shopId = '.$this->user_id.' and a.status = 1', $offset, $limit);
        }else{
            $orderlist = $this->apporder_model->getDealOrder(' a.shopId = '.$this->user_id.' and a.status > 2 and a.status < 100', $offset, $limit);
        }

        $this->success(array('data' => $orderlist, 'page' => $page));
    }

    /**
     * 预定订单详情
     */
    public function orderdetail()
    {
        if(!isset($_GET['id']) || !is_numeric($_GET['id'])) $this->error('order id not be null');
        $orderDetail = $this->apporder_model->dealOrderDetail(array('ao.shopId' => $this->user_id, 'ao.id' => $_GET['id']), 'deal');

        $this->success($orderDetail);
    }

    /**
     * 处理预定
     */
    public function dealorder()
    {
        if(!isset($_POST['id']) || !is_numeric($_POST['id'])) $this->error('order id not be null');
        if(!isset($_POST['action']) || !is_numeric($_POST['action'])) $this->error('action not be null');

		if($this->usertype!='GUIDER') $this->error('您不是玩伴，无法处理预定申请');
        if(!$orderInfo = $this->apporder_model
            ->orderDetail(array('ao.shopId' => $this->user_id, 'ao.id' => $_POST['id']))) $this->error('订单不存在');
        
        if($orderInfo['status_id']!=1) $this->error('预定已被处理');
        
        $reason = isset($_POST['reason']) && strip_tags(trim($_POST['reason'])) && $_POST['action'] ? strip_tags($_POST['reason']) : null;
        //同意：3 拒绝：2
        $status = $_POST['action'] == 1 ? 3 : 2;
        //更新订单
        $data = array('commentsSaler' => $reason, 'status' => $status, 'changed' => time());
        $where = array('id' => $_POST['id'], 'shopId' => $this->user_id);
        $update_res = $this->apporder_model->updateOrder($data, $where);
        if($update_res){
        	/*******玩伴同意******/
            if($status == 3){
            	//订单日志
                $this->apporderlog_model->addOrderLog(array(
                                                                'orderId' => $_POST['id'],
                                                                'log'     =>"玩伴接受了预定,行程将于".date('Y年m月d日',strtotime($orderInfo['startDay']))."开始",
                                                                'created' => time()
                                                            ));
                //提醒
                $start_date = date('Y年m月d日',strtotime($orderInfo['startDay']));
                //英文模板的短信不能出现中文
                $start_date_en = date('Y-m-d',strtotime($orderInfo['startDay']));
                $end_date = date('Y年m月d日',strtotime($orderInfo['stopDay']));
                $title = $orderInfo['orderName'];
                $people_num = $orderInfo['persons'];
                $money = $orderInfo['moneyTotalRMB'];
                
                $guider_info = $this->userv2_model->getUserv2(array('uid' => $orderInfo['shopId']));
                $tourist_info = $this->userv2_model->getUserv2(array('uid' => $orderInfo['uid']));
                //网页提醒（游客）
                $tourist_notice = $guider_info['userName']."接受了您的《{$title}》的申请，您可以前去个人中心我的订单中查看订单信息";
                $this->apporder_model->addNotice($guider_info['uid'], $tourist_info['uid'], $tourist_notice);
                //短信提醒
                $mobile_guider = '+'.$guider_info['telCode'].$guider_info['telNum'];
                $mobile_tourist = '+'.$tourist_info['telCode'].$tourist_info['telNum'];
                //发送短信(游客)
                if($tourist_info['telNum']){
                    $tpl_id = 1196375;
                    $tpl_value = "#tourist#={$tourist_info['userName']}}&#start_date#={$start_date}&#end_date#={$end_date}&#service#={$title}&#people_num#={$people_num}&#money#={$money}&#guide#={$guider_info['userName']}&#phone_num#={$mobile_guider}&#email#={$guider_info['email']}";
                    $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $mobile_tourist);
                }
                //发送短信(玩伴)
                if($guider_info['telNum']){
                    $tpl_id = 1196395;
                    $tpl_value = "#date#=".$start_date_en;
                    $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $mobile_guider);
                }
                //邮件提醒
                $einfo = array(
                    'title'      => $title,
                    'start_date' => $start_date,
                    'end_date'   => $end_date,
                    'people_num' => $people_num,
                    'money'      => $money,
                	'guider_name'              => $guider_info['userName'],
                	'mobile_guider'            => $mobile_guider,
                	'guider_mail'              => $guider_info['email'],
                	'guide_yudingjilu_address' => $this->url.'/guider/orders_paid',
                	'tourist_name' => $tourist_info['userName']
                );
                
                $bodytourist = $this->load->view('email/afterWanbanAccept-tourist',$einfo,true);
                $bodyguider = $this->load->view('email/afterWanbanAccept-guider',$einfo,true);
                //发送邮件（游客）
                if($tourist_info['email']){
                	$this->apporder_model->sendEmail("哇吖旅行",$tourist_info['email'],"预定成功",$bodytourist);                	 
                    //$this->myemail->send_mail($tourist_info['email'],'预定成功',$body['tourist']);
                }
                //发送邮件（玩伴）
                if($guider_info['email']){
                	$this->apporder_model->sendEmail("哇吖旅行",$guider_info['email'],"订单确认",$bodyguider);
                    //$this->myemail->send_mail($guider_info['email'],'订单确认',$body['guider']);
                }
            }else{
            	/*******玩伴拒绝******/
            	//订单日志
                $this->apporderlog_model->addOrderLog(array(
                    'orderId' => $_POST['id'],
                    'log'     =>"玩伴拒绝了预定,原因:$reason",
                    'created' => time()
                ));
                //提醒
                $title = $orderInfo['orderName'];
                $guider_info = $this->userv2_model->getUserv2(array('uid' => $orderInfo['shopId']));
                $tourist_info = $this->userv2_model->getUserv2(array('uid' => $orderInfo['uid']));
                $mobile_tourist = '+'.$tourist_info['telCode'].$tourist_info['telNum'];
                //网页提醒（游客）
                $tourist_notice = "{$guider_info['userName']} 拒绝了您《{$title}》的申请，原因如下：《{$reason}》，哇吖将在两个工作日之内向您执行原路退款操作。";
                $this->apporder_model->addNotice($guider_info['uid'], $tourist_info['uid'], $tourist_notice);
                //发送短信(游客)
                if($tourist_info['telNum']){
                    $tpl_id = 1196351;
                    $tpl_value = "#guide#={$guider_info['userName']}&#service#={$title}";
                    $this->mysms->send_sms_to_user_id($tpl_id, $tpl_value, $mobile_tourist);
                }
                //发送邮件(游客)
                if($tourist_info['email']){
                    $tourist_yudingjilu_address = $this->url.'/tourist/orders';
                    $einfo=array(
                    	"guider_name"=>$guider_info['userName'],
                    	"title"=>$title,
                    	"reason"=>$reason,
                    	"tourist_yudingjilu_address"=>$tourist_yudingjilu_address
                    );
                    $bodytourist = $this->load->view('email/afterWanbanReject-tourist',$einfo,true);
                    $this->apporder_model->sendEmail("哇吖旅行",$tourist_info['email'],"预定失败",$bodytourist);
                    //$this->myemail->send_mail($orderInfo['email'],'订单确认',$body['guider']);
                }
            }
        }else{
        	$this->error('更新订单状态失败');
        }
        $this->success();
    }

    /**
     * 评论列表
     */
    public function comments()
    {
        //页码
        $page = 1;
        if(isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page']>1){
            $page = $_GET['page'];
        }
        //$offset = ($page - 1) * $this->page_limit;
		$offset=0;
		//每页数量
        /*if(!isset($_GET['size']) || !is_numeric($_GET['size'])){
            $limit = $this->page_limit;
        }else{
            $limit = $_GET['size'];
		}*/
        $limit=$page*5;

        if(isset($_GET['iscomment']) && is_numeric($_GET['iscomment']) && $_GET['iscomment'] == 1){
            $whereData = array('uid' => $this->user_id, 'iscomment' => 1);
        }else{
            $whereData = array('uid' => $this->user_id, 'iscomment' => 0);
        }

        $commentsList = $this->trackcomments_model->getCommentsList($whereData, $offset, $limit);


        $this->success($commentsList);
    }
    
    /**
     * 评论页信息
     */
    public function getcommentinfo(){
        $id=isset($_GET['order_id'])?$_GET['order_id']:null;
    	if(empty($id)) $this->error('order id is null');
    	
    	$orderInfo = $this->apporder_model->getOrderBy(array('uid' => $this->user_id, 'id' => $id));
    	$guider=$this->userv2_model->getUserv2(array('uid'=>$orderInfo['shopId']),'userName,userIcon');
    	$ret=array('order_id'=>$orderInfo['id'],'userName'=>$guider['userName'],'userIcon'=>$guider['userIcon'],'orderName'=>$orderInfo['title']);
    	$this->success($ret);
    }

    /**
     * 景点评论页信息
     */
    public function getsceniccomment(){
    	$id=isset($_GET['scenic_id'])?$_GET['scenic_id']:null;
    	if(empty($id)) $this->error('scenic id is null');
    	
    	$info=$this->jingdian_model->detail($id);
    	if(!empty($info)){
    		$this->success(array('id'=>$info['id'],'name'=>$info['name']));
    	}else{
    		$this->error('景点不存在');
    	}    	
    }
    /**
     * 判断用户是否已经评论景点
     */
    public function isscenicremarked()
    {
    	$scenic_id = isset($_POST['scenic_id']) && is_numeric($_POST['scenic_id']) ? $_POST['scenic_id'] : null;
    	if($this->trackcomments_model->getSenicComments(array('uid' => $this->user_id, 'targetId' => $scenic_id)))
    	{
    		$this->error();
    	}else {
    		$this->success();
    	}
    	
    }
    /**
     * 添加景点评论
     */
    public function addsceniccomment(){
    	$scenic_id = isset($_POST['scenic_id']) && is_numeric($_POST['scenic_id']) ? $_POST['scenic_id'] : null;
    	$comments = isset($_POST['comments']) && strlen($_POST['comments']) ? $_POST['comments'] : null;
    	$images = isset($_POST['images']) && !empty($_POST['images']) ? $_POST['images'] : null;
    	$comments_pic='';
    	$comments_pic_arr=array();
    			
    	if($comments === null) $this->error('comments is null');
    	if($scenic_id === null) $this->error('scenic id is null');
    	
    	if(!$scenicInfo = $this->jingdian_model->detail($scenic_id))
    		$this->error('景点不存在');
    	
    	//fileReader Ajax提交方式
    	foreach($images as $k=>$image){
    		if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $image, $result)) {
    			$type = strtolower($result[2]);
    			$new_img_name = md5(uniqid()).'.'.$type;
    			//实际存储位置
    			$new_img_url = self::SCENIC_COMMENTS_PIC.$new_img_name;
    			//存入DB的url
    			$new_img_url_db = self::SCENIC_COMMENTS_PIC_INDB.$new_img_name;
    			$new_img = base64_decode(str_replace($result[1], '', $image));
    		
    			if (file_put_contents($new_img_url, $new_img)) {
    				$comments_pic.=$new_img_url_db.';';
    				$comments_pic_arr[]=$new_img_url;
    			}else{
    				$this->error('图片上传出错，请重试');
    			}
    		}
    	}
    	
    	//处理图像
    	$this->config->load('imagelib',true);
    	$config['width']=$this->config->item('scenic_comments_pic_width','imagelib');
    	$config['quality']=$this->config->item('quality','imagelib');
    	$config['master_dim']=$this->config->item('master_dim','imagelib');
    	
    	$this->load->library('image_lib');
    	foreach ($comments_pic_arr as $k=>$url){    		
    		$config['source_image'] = $url;
    		$config['new_image'] = $url;
    		
    		$this->image_lib->clear();
    		$this->image_lib->initialize($config);
    		
    		if ( ! $this->image_lib->resize())
    		{
    			log_message('error', $this->image_lib->display_errors());
    		}
    		
    	}
    	
    	//form提交方式，批量添加图片，作废
    	/*$config['upload_path'] = self::SCENIC_COMMENTS_PIC;
    	
    	$this->load->library('Myupload',$config);
    	$comments_pic = '';
    	$file_arr = array();
    	if($_FILES['comments_pic']){
    		$cou=count($_FILES['comments_pic']['name']);
    		for($i = 0; $i < $cou ;$i++){
    			if($_FILES['comments_pic']['name'][$i]){
    			$file_arr[$i]['name'] = $_FILES['comments_pic']['name'][$i];
    			$file_arr[$i]['type'] = $_FILES['comments_pic']['type'][$i];
    			$file_arr[$i]['tmp_name'] = $_FILES['comments_pic']['tmp_name'][$i];
    			$file_arr[$i]['error'] = $_FILES['comments_pic']['error'][$i];
    			$file_arr[$i]['size'] = $_FILES['comments_pic']['size'][$i];
    			}
    		}
    	}
    	
    	foreach($file_arr as $k => $v) {
    		$_FILES['comments_pic'] = $v;
    		$identityRes = $this->myupload->doUpload('comments_pic');
    		if ($identityRes['code']) {
    			$comments_pic .= self::SCENIC_COMMENTS_PIC_INDB.$identityRes['data']['upload_data']['file_name'].';';
    		} else {
    			$this->error('评论图片上传失败'.$identityRes['data']['error']);
    		}
    	
    	}*/
    	
    	//添加评论
    	$ret=$this->trackcomments_model->addSenicComments(array('uid' => $this->user_id,
    			'targetId'     => $scenic_id,
    			'tourist_pic'  => $comments_pic,
    			'comments'     => $comments,
    			'created'      => time()
    	));
    	if($ret){
    		$this->success('评论成功');
    	}else{
    		$this->error('系统错误，请重试');
    	}
    }
    /**
     * 添加评论
     */
    public function addcomment()
    {
    	$guider_score = isset($_POST['guider_score']) && is_numeric($_POST['guider_score']) ? $_POST['guider_score'] : null;
        $track_score = isset($_POST['track_score']) && is_numeric($_POST['track_score']) ? $_POST['track_score'] : null;
        $order_id = isset($_POST['order_id']) && is_numeric($_POST['order_id']) ? $_POST['order_id'] : null;
        $comments = isset($_POST['comments']) && strlen($_POST['comments']) ? $_POST['comments'] : null;
        //$type = isset($_POST['type']) && strlen($_POST['type']) && in_array($_POST['type'], array('TRACK', 'ACTIVITY', 'ZIYING')) ? $_POST['type'] : null;

        if($guider_score === null) $this->error('guider_score is null');
        if($track_score === null) $this->error('track_score is null');
        if($comments === null) $this->error('comments is null');
        //if($type === null) $this->error('type is null');
        if($order_id === null) $this->error('order id is null');

        if(!$orderInfo = $this->apporder_model
                ->getOrderBy(array('uid' => $this->user_id, 'id' => $order_id))) 
        	$this->error('订单不存在');

        if($this->trackcomments_model->getComments(array('uid' => $this->user_id, 'oid' => $orderInfo['orderNo']))) 
        	$this->error('该订单已经评论');

        //批量添加图片
		$config['upload_path'] = self::COMMENTS_PIC;
        
        $this->load->library('Myupload',$config);
        $comments_pic = '';
        $file_arr = array();
        if($_FILES['comments_pic']){
        	$cou=count($_FILES['comments_pic']['name']);
            for($i = 0; $i < $cou ;$i++){
                $file_arr[$i]['name'] = $_FILES['comments_pic']['name'][$i];
                $file_arr[$i]['type'] = $_FILES['comments_pic']['type'][$i];
                $file_arr[$i]['tmp_name'] = $_FILES['comments_pic']['tmp_name'][$i];
                $file_arr[$i]['error'] = $_FILES['comments_pic']['error'][$i];
                $file_arr[$i]['size'] = $_FILES['comments_pic']['size'][$i];
            }       	
        }

        foreach($file_arr as $k => $v) {
            $_FILES['comments_pic'] = $v;
            $identityRes = $this->myupload->doUpload('comments_pic');
            if ($identityRes['code']) {
                $comments_pic .= self::COMMENTS_PIC_INDB.$identityRes['data']['upload_data']['file_name'].';';
                //处理图片
                $config2['source_image'] = self::COMMENTS_PIC.$identityRes['data']['upload_data']['file_name'];
                $config2['width']     = 500;
                $config2['height']   = 350;
                $this->load->library('image_lib', $config2);
                $this->image_lib->resize();
            } else {
                $this->error('评论图片上传失败'.$identityRes['data']['error']);
            }

        }

        //添加评论
        $ret=$this->trackcomments_model->addComments(array('uid' => $this->user_id,
                                                      'oid'          => $orderInfo['orderNo'],//orderNo不是orderId
                                                      'track_id'     => $orderInfo['goodsId'],
                                                      'track_name'     => $orderInfo['title'],
                                                      'tourist_pic'  => $comments_pic,
                                                      'comments'     => $comments,
                                                      'persons'      => $orderInfo['persons'],
                                                      'guider_id'    => $orderInfo['shopId'],
                                                      'track_score'  => $track_score,
                                                      'guider_score' => $guider_score,
                                                      'type'         => $orderInfo['goodsType'],
                                                      'created'      => time()
                                                      ));
        if(!empty($ret)){
        	//更新订单状态
        	$this->apporder_model->updateOrder(array('status'=>7),array('id'=>$orderInfo['id']));
        	//获取线路的平均得分
        	$avg=$this->trackcomments_model->getAvgScore(array('track_id'=> $orderInfo['goodsId']));
        	$save['score']=$avg['avg_score']*100;
        	switch ($orderInfo['goodsType']){
        		case 'TRACK':
        			$this->trackcomments_model->updateAvgScore($save,'mod_track',array('id'=>$orderInfo['goodsId']));
        			break;
        		case 'ACTIVITY':
        			$this->trackcomments_model->updateAvgScore($save,'mod_activity',array('id'=>$orderInfo['goodsId']));;
        			break;
        		case 'ZIYING':
        			$this->trackcomments_model->updateAvgScore($save,'mod_ziying',array('id'=>$orderInfo['goodsId']));
        			break;
        		default:
        			$this->error('线路类型不存在');
        			break;
        	}
        	//订单日志
        	$this->apporderlog_model->addOrderLog(array('orderId' => $orderInfo['id'],
        			'log' =>"游客进行了评价",'created' => time()));
        	$this->success();
        }else{
        	$this->error('添加评论失败');
        }
        
    }

    /**
     *
     *
     * 验证身份
     */
    public function checkidentity()
    {
        $data['job']   = isset($_POST['job']) && strlen($_POST['job']) ? $_POST['job'] : null;
        $data['major']   = isset($_POST['major']) && strlen($_POST['major']) ? $_POST['major'] : null;
        $data['school']   = isset($_POST['school']) && strlen($_POST['school']) ? $_POST['school'] : null;        
        $save['identityName']   = isset($_POST['identityName']) && strlen($_POST['identityName']) ? $_POST['identityName'] : null;
        
        if(!$save['identityName']) $this->error('请选择身份');
        if($save['identityName']=='留学生'){
        	if(!$data['school']||!$data['major'])
        		$this->error('请填写学校和专业');
        }else{
        	if(!$data['job'])
        		$this->error('请填写工作领域');
        }
        if(empty($_FILES))
        	$this->error('请上传身份和职业证件照片');
        
        //所在学校、所学专业和工作领域
        if(empty($data['job'])){
        	$save['identityErea'] = $data['major'].'-|-'.$data['school'];
        }else{
        	$save['identityErea'] = $data['job'];
        }      
        //修改状态为认证中
        $save['identityActive'] = 0;
        $save['changed']        = time();
        
        $identityPic = $certificatePic = $save['identityPicture'] = '';
        //上传身份照片        
        $this->load->library('Myupload', array('upload_path' => self::IDENTITY_PIC));
        $identityRes = $this->myupload->doUpload('identity_pic');
        if($identityRes['code']){
            $identityPic = self::IDENTITY_PIC_INDB.$identityRes['data']['upload_data']['file_name'];
        }else{
            $this->error('身份证件上传失败');
        }
        //上传职业照片
        $this->load->library('Myupload', array('upload_path' => self::IDENTITY_PIC));
        $certificateRes = $this->myupload->doUpload('certificate_pic');
        if($certificateRes['code']){
            $certificatePic = self::IDENTITY_PIC_INDB.$certificateRes['data']['upload_data']['file_name'];
        }else{
            $this->error('职业证件上传失败');
        }
        if($certificatePic || $identityPic) 
        	$save['identityPicture'] = $identityPic.';'.$certificatePic;

        //更新身份信息
        $this->userv2_model->editUser($save, array('uid' => $this->user_id));

        $this->success();
    }

    /**
     * 获取身份信息
     */
    public function getidentity()
    {
        $res = $this->userv2_model->getUserv2(array('uid' => $this->user_id), 'identityPicture,identityErea,identityName,identityActive,utype');
        if($res['utype']!='GUIDER') $this->error('游客账户不能进行身份认证');
        unset($res['utype']);
        //statusName:按钮文本
        if(!empty($res['identityActive'])){
        switch ($res['identityActive']){
        	case 0:
        		$res['statusName']='审核中';
        		$res['disable']=1;
        		break;
        	case 1:
        		$res['statusName']='已认证';
        		$res['disable']=1;
        		break;
        	case 2:
        		$res['statusName']='重新认证';
        		$res['disable']=0;
        		break;
        	default:
        		$res['statusName']='去认证';
        		$res['disable']=0;
        		break;        		
        }
        }else{
        	$res['statusName']='去认证';
        	$res['disable']=0;
        }
        //所在学校、所学专业和工作领域
        switch ($res['identityName']){
        	case "留学生":
        		$res['schoolAndMajorHide']=0;
        		$res['jobHide']=1;
        		$info=explode('-|-',$res['identityErea']);
        		$res['major']=$info[0];
        		$res['school']=$info[1];
        		$res['job']='';
        		break;
        	case "当地华人":
        		$res['schoolAndMajorHide']=1;
        		$res['jobHide']=0;
        		$res['job']=$res['identityErea'];
        		$res['major']='';
        		$res['school']='';
        	case "外国人":
        		$res['schoolAndMajorHide']=1;
        		$res['jobHide']=0;
        		$res['job']=$res['identityErea'];
        		$res['major']='';
        		$res['school']='';
        	default:
        		$res['schoolAndMajorHide']=0;
        		$res['jobHide']=0;
        		$res['job']='';
        		$res['major']='';
        		$res['school']='';
        }
        unset($res['identityErea']);
        //分开身份证件和职业证件
        list($res['identityPicture'],$res['certificatePicture'])
        = $res['identityPicture'] ? explode(';', $res['identityPicture']) : array('', '');
        
        $this->success($res);
    }

    /**
     * 修改基本信息
     */
    public function edituserinfo()
    {
        $userdata=array();
        $userinfodata=array();
        //$this->success($_POST);
        if(!empty($_POST)){
        	if(isset($_POST['userFamily']) && strlen($_POST['userFamily'])){
        		$userinfodata['userFamily'] = trim($_POST['userFamily']);
        	}
        	if(isset($_POST['userName']) && strlen($_POST['userName'])){
        		$userinfodata['userName'] = trim($_POST['userName']);
        	}
        	//user_v2 userName
        	if(isset($userinfodata['userName']) && isset($userinfodata['userFamily'])){
        		$userdata['userName']=$userinfodata['userFamily'].$userinfodata['userName'];
        	}
        	if(isset($_POST['userGender']) && in_array($_POST['userGender'], array('f', 'm'))){
        		$userinfodata['userGender']  = $_POST['userGender'];
        		//user_v2 userGender
        		$userdata['userGender'] = $_POST['userGender'];
        	}
        	if(isset($_POST['introduction']) && strlen($_POST['introduction'])){
        		$userinfodata['introduction'] = $_POST['introduction'];
        	}
        	if(isset($_POST['userAge']) && strlen($_POST['userAge'])){
        		$userinfodata['userAge'] = $_POST['userAge'];
        	}
        	if(isset($_POST['nationality']) && strlen($_POST['nationality'])){
        		$userinfodata['nationality'] = trim($_POST['nationality']);
        	}
        	if(isset($_POST['resideCity']) && strlen($_POST['resideCity'])){
        		$userinfodata['resideCity'] = trim($_POST['resideCity']);
        	}
        	if(isset($_POST['resideTime']) && strlen($_POST['resideTime'])){
        		$userinfodata['resideTime'] = $_POST['resideTime'];
        	}
        	//fileReader Ajax提交方式
	        if(isset($_POST['userIcon']) && strlen($_POST['userIcon'])){
	        	$userIcon=$_POST['userIcon'];	        	        	 
	        	if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $userIcon, $result)) {
	        		$type = strtolower($result[2]);
	        		$new_img_name = md5(uniqid()).'.'.$type;
	        		//实际存储位置
	        		$new_img_url = self::USERICON_PIC.$new_img_name;
	        		//存入DB的url
	        		$new_img_url_db = self::USERICON_PIC_INDB.$new_img_name;
	        		$new_img = base64_decode(str_replace($result[1], '', $userIcon));
	        	
	        		if (file_put_contents($new_img_url, $new_img)) {
	        			$userinfodata['userIcon']=$new_img_url_db;
	        			//user_v2 userIcon
	        			$userdata['userIcon']=$new_img_url_db;
	        		}else{
	        			$this->error('图片上传出错，请重试');
	        		}
	        	
	        	}
	        }	        
        }
        //处理图像
        $this->config->load('imagelib',true);
        $config['width']=$this->config->item('user_icon_width','imagelib');
        $config['quality']=$this->config->item('quality','imagelib');
        $config['master_dim']=$this->config->item('master_dim','imagelib');
         
        $this->load->library('image_lib');
        $config['source_image'] = $new_img_url;
        $config['new_image'] = $new_img_url;
        
        $this->image_lib->clear();
        $this->image_lib->initialize($config);
        
        if ( ! $this->image_lib->resize())
        {
        	log_message('error', $this->image_lib->display_errors());
        }
	        //form提交方式，添加图片，作废
//         if(isset($_FILES['userIcon'])){
//         	//上传图片
//         	$config['upload_path'] = self::USERICON_PIC;
//         	$this->load->library('Myupload', $config);
//         	$userIconRes = $this->myupload->doUpload('userIcon');
//         	if($userIconRes['code']){
//         		$userIcon = self::USERICON_PIC_INDB.$userIconRes['data']['upload_data']['file_name'];
//         		//处理图片
//         		$config2['source_image'] = self::USERICON_PIC.$userIconRes['data']['upload_data']['file_name'];
//         		$config2['width']     = 200;
//         		$config2['height']   = 200;
//         		$this->load->library('image_lib', $config2);
//         		$this->image_lib->resize();
//         	}else{
//         		$this->error('头像上传失败['.$userIconRes['data']['error'].']');
//         	}
       	
//         	$userdata['userIcon'] = $userinfodata['userIcon'] = $userIcon;
//         }
        
        if(!empty($userdata)){
        	if(!$this->userv2_model->editUser($userdata, array('uid' => $this->user_id))){
        		$this->error('网络状态异常，请重试');
        	}
        }
        if(!empty($userinfodata)){
        	if(!$this->userv2info_model->editUserInfo($userinfodata, array('uid' => $this->user_id))){
        		$this->error('网络状态异常，请重试');
        	}
        }        
        
        $this->success();
    }

    /**
     * 验证手机号
     */
    public function validatemobile()
    {
        $phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? trim($_POST['phoneNum']) : null;
        $areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? trim(ltrim($_POST['areaCode'], '+')) : null;
        $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
        $smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));
		//表单检查
        if(!$phone) $this->error('请输入手机号码');
		if(!$areaCode) $this->error('请选择手机区号');
		//短信验证码
        if(!$smsCode['status']){
        	$this->error($msg);
        }else {
        	if($smsCode['code'] != $securimage_code_value) $this->error('验证码不正确');
        	 
        }
        //用户是否已存在
        if($this->userv2_model->getUserv2(array('telNum' => $phone))) $this->error('该手机号已被注册');
        $data = array(
            'telNum'     => $phone,
            'telActive'  => 1,
            'changed'    => time(),
            'telCode'    => $areaCode,
            'utype'      => $utype,
        );
        //更新用户信息
        $uid = $this->userv2_model->editUser($data, array('uid' => $this->user_id));
        if($uid > 0){
            $this->userv2info_model->editUserInfo(array('userPhone' => "+".$areaCode.trim($phone)), array('uid' => $this->user_id));
            $this->success();
        }else{
            $this->error('系统错误请重试');
        }
    }

    /**
     * 邮箱发送验证码
     */
    public function sendemailcode()
    {
        $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? $_POST['email'] : null;
        if($email === null) $this->error('邮箱格式不正确');
        
        $status = $this->myusersubscribe->user_activation_code($email);
        if(!$status){
            $this->error('邮件发送失败请重试');
        }else{
            $this->success('邮件发送成功');
        }
    }

    /**
     * 验证邮箱
     */
    public function validateemail()
    {
        $email = isset($_POST['email']) && strlen($_POST['email']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ? trim($_POST['email']) : null;
        $securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
        
        if($email === null) $this->error('邮箱格式不正确');
        $res=check_email_code_value($securimage_code_value);
        if($res==2) $this->error('验证码已过期,请重新发送');
        if($res==3) $this->error('验证码错误');
        
        
        if($this->userv2_model->getUserv2(array('userId' => $email))) $this->error('该邮箱已被注册');

        $data = array(
        	'userId'  =>$email,
            'email'   => $email,
            'changed' => time(),
            'status'  => 1,
            'active'  => 1,
        );
        $uid = $this->userv2_model->editUser($data, array('uid' => $this->user_id));
        if($uid > 0){
            $this->success();
        }else{
            $this->error('系统错误请重试');
        }
    }
    
    /**
     * 账户设置主页
     */
    public function editAccount(){
    	//手机绑定
    	$data=$this->userv2_model->getUserv2(array('uid'=>$this->user_id));
    	if($data['telActive']!=1||empty($data['telNum'])){
    		$ret1=array('istelbinded'=>0,'telcached'=>'');
    	}else{
    		$tel=substr(trim($data['telNum']), 0, 3);
    		$tel.="****";
    		$tel.=substr(trim($data['telNum']), -4);
    		$ret1=array('istelbinded'=>1,'telcached'=>$tel);
    	}
    	//邮箱绑定
    	if(empty($data['userId'])||$data['active']!=1){
    		$ret2=array('isemailbinded'=>0,'emailcached'=>'');
    	}else{
    		$email=substr(trim($data['userId']), 0, 3);
    		$email.="****";
    		$email.=substr(trim($data['userId']), strpos($data['userId'], '@'));
    		$ret2=array('isemailbinded'=>1,'emailcached'=>$email);
    	}
    	$this->success(array_merge($ret1,$ret2));
    	
    }
    
    /**
     * 修改密码
     */
    public function editpassword()
    {
        if(empty($_POST)){
        	$data=$this->userv2_model->getUserv2(array('uid'=>$this->user_id));
        	if($data['telActive']!=1||empty($data['telNum'])){
        		$ret=array('isbinded'=>0,'telcached'=>'','phoneNum'=>'','areaCode'=>'');
			    $this->success($ret);
			}else{
        		$tel=substr(trim($data['telNum']), 0, 3);
        		$tel.="****";
        		$tel.=substr(trim($data['telNum']), -4);
        		$ret=array('isbinded'=>1,'telcached'=>$tel,'phoneNum'=>$data['telNum'],'areaCode'=>$data['telCode']);
		        $this->success($ret);
			}
        }else{
        	$password = isset($_POST['password']) && strlen($_POST['password'])? $_POST['password'] : null;
        	$re_password = isset($_POST['re_password']) && strlen($_POST['re_password'])? $_POST['re_password'] : null;
        	$phone = isset($_POST['phoneNum']) && strlen($_POST['phoneNum']) ? trim($_POST['phoneNum']) : null;
        	$areaCode = isset($_POST['areaCode']) && strlen($_POST['areaCode']) ? trim(ltrim($_POST['areaCode'], '+')) : null;
        	$securimage_code_value = isset($_POST['securimage_code_value']) && strlen($_POST['securimage_code_value'])? $_POST['securimage_code_value'] : null;
			//表单检查
			if(!$password) $this->error('请输入新密码');
			if($re_password) $this->error('请再次输入密码');
			if(!$phone) $this->error('请输入手机号码');
			if(!$areaCode) $this->error('请选择手机区号');
			if($re_password != $password) $this->error('两次密码输入不相同');
        	//短信验证码
        	$smsCode = $this->userv2mobile_model->getSmsCode(array('mobile' => '+'.$areaCode.$phone));
        	if(!$smsCode['status']){
        		$this->error($msg);
        	}else {
        		if($smsCode['code'] != $securimage_code_value) $this->error('验证码不正确');
        	
        	}
        	//判定用户是否绑定过手机
        	$data=$this->userv2_model->getUserv2(array('uid'=>$this->user_id));
        	//未绑定
        	if($data['telActive']!=1||empty($data['telNum'])){
        		if($this->userv2_model->getUserv2(array('telNum' => $phone))) $this->error('该手机号已被注册');
        		$update = array(
        				'telNum'     => $phone,
        				'telActive'  => 1,
        				'changed'    => time(),
        				'telCode'    => $areaCode,
        				'userToken'  => md5($password)
        		);
        		$updateinfo=array('userPhone' => "+".$areaCode.$phone);
        	}else{
        	//已绑定
        		if($data['telNum']!=$phone) $this->error('手机号码与绑定的号码不同');
        		$update = array(
        				'changed'    => time(),
        				'userToken'  => md5($password)
        		);
        	}
            //更新用户信息    
        	$uid = $this->userv2_model->editUser($update,array('uid'=>$this->user_id));
        	if($uid > 0){
        		if(isset($updateinfo)){
        			if(!$this->userv2info_model->editUserInfo($updateinfo,array('uid'=>$this->user_id)))
        			{
        				$updateinfo=array_merge($updateinfo,array('uid'=>$this->user_id));
        				$this->userv2info_model->createUserV2Info($updateinfo);
        			}
        		}
        		$this->success();
        	}else{
        		$this->error('系统错误请重试');
        	}
        }
    	
    }

    /**
     * 验证用户手机号是否验证
     */
    public function getmobile()
    {
        if($res = $this->userv2_model->getUser(array('uid' => $this->user_id, 'telActive' => 1), 'telNum,telCode')){
            $this->success($res);
        }else{
            $this->error();
        }
    }

    /**
     * 聊天记录列表
     */
    public function chat()
    {
        $rev_id = isset($_GET['rev_id']) && is_numeric($_GET['rev_id'])? $_GET['rev_id'] : null;
        $page = isset($_GET['page']) && $_GET['page']>0 && is_numeric($_GET['page']) ? $_GET['page']:1;
        if($rev_id === null) $this->error('聊天对象id不能为空');
        if($rev_id==$this->user_id) $this->error('聊天对象不能为自己');

        if($_SESSION['user_type'] == 'GUIDER'){
            $where = 'uc.uid = '.$rev_id.' and uc.guiderId = '.$this->user_id;
        }else{
            $where = 'uc.uid = '.$this->user_id.' and uc.guiderId = '.$rev_id;
        }
        $data = $this->userchat_model->getChatList($where,$page,$this->user_id,$rev_id);
        $this->success($data);
    }

    /**
     * 私信列表
     */
    public function getchatgroup()
    {
    	if(empty($_GET['page'])||$_GET['page']<1||!is_numeric($_GET['page']))
    	{$page=1;}
    	else
    	{$page=$_GET['page'];}
    	
        $data = $this->userchat_model->getChatByUser($this->user_id, $_SESSION['user_type'],$page);
        $this->success($data);
    }

    /**
     * 添加聊天消息
     */
    public function addchat()
    {
        $rev_id = isset($_POST['rev_id']) && is_numeric($_POST['rev_id']) ? $_POST['rev_id'] : null;
		if($rev_id==$this->user_id) $this->error('聊天对象不能为自己');
		$text = isset($_POST['text']) && strlen($_POST['text'])? $_POST['text'] : null;
        if($rev_id === null) $this->error('聊天对象id不能为空');

        if (! empty($text))
        {
            $text = htmlspecialchars($text);
            $text = nl2br($text);
        }

        if(stripos($text,'#') !== FALSE){
            $search =array(
                "#呵呵#", "#哈哈#","#吐舌#", "#啊#","#酷#","#怒#", "#开心#", "#汗#", "#泪#", "#黑线#",
                "#鄙视#", "#不高兴#", "#真棒#", "#钱#", "#疑问#", "#阴脸#", "#吐#", "#咦#", "#委屈#",
                "#花心#", "#呼~#", "#笑脸#", "#冷#", "#太开心#", "#滑稽#", "#勉强#", "#狂汗#", "#乖#",
                "#睡觉#", "#惊哭#", "#生气#", "#惊讶#", "#喷#", "#爱心#", "#心碎#", "#玫瑰#", "#礼物#",
                "#彩虹#", "#星星月亮#", "#太阳#", "#钱币#", "#灯泡#","#茶杯#", "#蛋糕#", "#音乐#",
                "#haha#","#胜利#","#大拇指#", "#弱#","#OK#");
            foreach($search as $k=>$v){
                $k++;
                $text = str_replace($v, "<img src=\"".$this->url."/resource/skin/face/tieba/".$k.".png\" />", $text);
            }
        }
        //读取缓存
        $this->load->driver('cache',array('adapter' => 'apc', 'backup' => 'file'));
        $cache_id = 'chat_'.$this->user_id."_".$rev_id;
        $unread=$this->cache->get($cache_id);
        //第一次发送消息或是缓存过期
		if(empty($unread)){
			$unread=array();
        	$unread['total'] = 0;
        	$unread['msg'] = '';
        	//本次发送时间
        	$unread['time'] = time();
        	//上次发送时间
        	$unread['last'] = time();
        }
        //与上一条消息的时间差
        $dif=time()-$unread['time'];
        $dif=abs($dif);
        //判定对方是否在线
        $login=$this->userv2_model->checkUserLogin($rev_id);
        //对方不在线且消息间隔时间为1个小时以上提醒对方
        if($login['islogin']!=1 && $dif>3600){
        	if($this->usertype=='GUIDER'){
        		$touristid=$this->user_id;
        		$guiderid=$rev_id;
        	}else{
        		$touristid=$rev_id;
        		$guiderid=$this->user_id;
        	}
        	$this->userchat_model->noticeOffline($touristid,$guiderid,$this->usertype);
        }
		//更新缓存
		$cachedata=array();
        $cachedata['total']=$unread['total']+1;
        $cachedata['msg']=$text;
        $cachedata['time']=time();
        $cachedata['last']=$unread['time'];       
        $this->cache->save($cache_id, $cachedata,86400*10);
        
        if($_SESSION['user_type'] == 'GUIDER'){
            $this->userchat_model->addChat(array('uid' => $rev_id, 'guiderId' => $this->user_id, 'fromUser' => 0, 'status' => 1, 'message' => $text, 'created' => time()));
        }else{
            $this->userchat_model->addChat(array('uid' => $this->user_id, 'guiderId' => $rev_id, 'fromUser' => 1, 'status' => 1, 'message' => $text, 'created' => time()));
        }

        $this->success();
    }

}
